<template>
	<view class="warp">
		<view class="nav">
			<!-- <view class="nav-item">
				<text class="title">团队人数</text>
				<text class="num">{{teamUsers}}</text>
			</view> -->
			<view class="nav-item">
				<text class="title">可提现金额</text>
				<text class="num">￥{{userInfo.money/100 || 0}}</text>
				<uni-tag text="提现" type="primary" @click="onClick"></uni-tag>
				<view style="color: #7272ff;font-size: 12px;padding: 10px 0;">100元起，D+1到账（服务费0.6%+单笔3元提现费）</view>
			</view>
			<!-- <view class="nav-item">
				<text class="title">分润订单</text>
				<text class="num">{{orderNum}}</text>
			</view> -->
		</view>
		<!-- <uni-segmented-control :current="sindex" :values="items" @clickItem="onClickItem" styleType="text" /> -->
		<view style="display: flex;justify-content: space-around;align-items: center;">
			<view v-for="(item,index) in segData" :key="index" @click="onClickItem(index)" class="seg-box"
				:class="{active:index==sindex}">
				<text style="font-weight: 700;">{{item.text}}</text>
				<text style="font-size: 15px;">{{item.value}}</text>
			</view>
		</view>
		<view class="" v-show="sindex == 0">
			<unicloud-db v-slot:default="{data, loading,pagination,hasMore, error, options}" :collection="collection"
				@load="load" ref="udbRef" :getcount="true">
				<uni-section title="分润订单详情" type="line">
					<uni-list>
						<uni-list-item v-for="(item) in data" :key="item._id">
							<template v-slot:body>
								<view class="box">
									<view class="price">￥{{item.price/100}}</view>
									<view class="body">
										<view class="title">{{item.commit}}</view>
										<view class="">{{item?.uid[0]?.nickname}}</view>
										<uni-dateformat :date="item.create_time"
											:threshold="[60000, 3600000]"></uni-dateformat>
									</view>
									<view class="bottom">
										<uni-tag v-if="item.type == 0" text="退款" type="warning"></uni-tag>
										<uni-tag v-if="item.type == 1" text="收入" type="success"></uni-tag>
									</view>
								</view>
							</template>
						</uni-list-item>
						<uni-load-state @networkResume="refresh" :state="{data,pagination,hasMore, loading, error}"
							@loadMore="loadMore">
						</uni-load-state>
					</uni-list>
				</uni-section>
			</unicloud-db>
		</view>
		<view class="" v-show="sindex == 1">
			<unicloud-db v-slot:default="{data, loading, error, options}" collection="wolf-tixian" ref="udbtRef"
				orderby="create_time desc" :where="twhere">
				<uni-section title="提现订单详情" type="line">
					<uni-list>
						<uni-list-item v-for="(item) in data" :key="item._id">
							<template v-slot:body>
								<view class="box">
									<view class="price">￥{{item.price/100}}</view>
									<view class="body">
										<uni-dateformat :date="item.create_time"
											:threshold="[60000, 3600000]"></uni-dateformat>
									</view>
									<view class="bottom">
										<uni-tag v-if="item.status == 0" text="提现中" type="warning"></uni-tag>
										<uni-tag v-if="item.status == 1" text="完成" type="success"></uni-tag>
										<uni-tag v-if="item.status == 2" text="失败"></uni-tag>
									</view>
								</view>
							</template>
						</uni-list-item>
					</uni-list>
				</uni-section>
			</unicloud-db>
		</view>

		<view class="" v-show="sindex == 2">
			<uni-section title="市场伙伴" type="line">
				<uni-list>
					<uni-list-item v-for="(item) in huoban" :key="item?.uid"  @click="navigator(item?.uid)" clickable>
						<template v-slot:body>
							<view class="box">
								<image :src="item.avatar || item.avatarFile?.url" mode="aspectFill" class="yImage">
								</image>
								<view class="section">
									<view class="item">{{item?.nickname}} [{{localHuoban[item?.newLevel || 0]}}]</view>
									<uni-dateformat :date="item?.inviteTime" />
								</view>
							</view>
						</template>
					</uni-list-item>
				</uni-list>
			</uni-section>
		</view>
		<!-- <view class="" v-show="sindex == 3">
			<uni-section title="红娘明细" type="line">
				<uni-list>
					<uni-list-item v-for="(item) in redList" :key="item.uid">
						<template v-slot:body>
							<view class="box">
								<image :src="item.avatar || item.avatarFile?.url" mode="aspectFill" class="yImage">
								</image>
								<view class="section">
									<view class="item">
										<text>{{item.nickname}}</text>
										<text>{{item.mobile}}</text>
									</view>
									<uni-dateformat :date="item.upred_time" />
								</view>
							</view>
						</template>
					</uni-list-item>
				</uni-list>
			</uni-section>
		</view> -->

		<!-- //粉丝明细 -->
		<view class="" v-show="sindex == 3">
			<uni-section title="粉丝明细" type="line">
				<userList />
			</uni-section>
		</view>
		
		<!-- //幸福值明细 -->
		<view class="" v-show="sindex == 4">
			<uni-section title="幸福值明细" type="line">
				<wolfHappiness :openid='openid'/>
			</uni-section>
		</view>


		<uni-popup ref="popup" type="bottom">
			<view class="pbox">
				<view class="header">上传提现二维码</view>
				<uni-forms ref="form" :modelValue="formData" label-width="150rpx">
					<uni-forms-item label="提现金额" name="price">
						<uni-easyinput v-model.number="formData.price" placeholder="" @change="priceChange">
							<template v-slot:right>
								<view style="color: blue;">元</view>
							</template>
						</uni-easyinput>
						<text>实际到账<text style="color: red;">{{con_price/100}}</text></text>
					</uni-forms-item>
					<uni-forms-item label="提现方式" name="type">
						<uni-data-checkbox  v-model="formData.type" :localdata="localType" />
						<text v-if="formData.type===0">自动提现：D+1到账</text>
						<text v-if="formData.type===1">人工提现：每周二审核到账</text>
					</uni-forms-item>
					<uni-forms-item label="提现二维码" name="img" v-if="formData.type===1">
						<uni-file-picker v-model="formData.img" limit="1" return-type="object"
							:imageStyles="imageStyles"></uni-file-picker>
					</uni-forms-item>
				</uni-forms>
				<button type="primary" size="mini" @click="submit">提现</button>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		useUserStore
	} from "@/pinia/user.js"
	import {
		mapState,
		mapActions
	} from "pinia"
	import userList from "./components/user-list.vue"
	import wolfHappiness from "./components/happiness.vue"
	// console.log("happiness",happiness,userList);
	const db = uniCloud.database();
	const User = uniCloud.importObject('uni-id-co')
	const uniPayCo = uniCloud.importObject("uni-pay-co");
	var myOpenid; // 将openid临时缓存，避免重复获取openid
	
	
	function getWeekDate() {
		var now = new Date();
		var day = now.getDay();
		var weeks = new Array(
			"周日",
			"周一",
			"周二",
			"周三",
			"周四",
			"周五",
			"周六"
		);
		var week = weeks[day];
		return week;
	}
	export default {
		components: {
			userList,
			wolfHappiness
		},
		data() {
			return {
				openid:'',
				teamUsers: 0,
				orderNum: 0,
				imageStyles: {
					width: 100,
					height: 100,
				},
				formData: {
					img: {},
					price: 0,
					type:0
				},
				sindex: 0,
				// items: ['分润订单', '提现订单', '平级月老', '下级红娘', '我的粉丝'],
				segData: [{
					text: "分润订单",
					value: 0
				}, {
					text: "提现订单",
					value: 0
				}, {
					text: "市场伙伴",
					value: 0
				}
				// , {
				// 	text: "下级红娘",
				// 	value: 0
				// }
				, {
					text: "我的粉丝",
					value: 0
				}, {
					text: "幸福值",
					value: 0
				}],
				yue: [], //月老列表
				redList: [], //红娘列表
				huoban:[],
				localHuoban:['普通会员','幸福使者','幸福大使','幸福天使','联合创始人'],
				localType:[{
					value:0,
					text:"自动提现"
				},{
					value:1,
					text:"人工付款"
				}],//提现类型
			}
		},
		computed: {
			...mapState(useUserStore, ["userInfo", "updateUserInfo"]),
			collection() {
				return [
					db.collection('wolf-profit-order').where(`pid == '${this.userInfo._id}'`).orderBy(
						'create_time desc').getTemp(),
					db.collection('uni-id-users').field('_id,nickname').getTemp()
				]
			},
			twhere() {
				return `uid == '${this.userInfo._id}'`
			},
			con_price() {
				let price = this.formData.price * 100 - this.formData.price * 0.6 - 300
				if (price <= 0) {
					price = 0
				}
				return Math.floor(price)
			}
		},
		async mounted() {
			let code;
			let res;
			if (!myOpenid) {
				// #ifdef MP-WEIXIN
				code = await this.getCode();
				res = await this.getOpenid({
					provider: "wxpay",
					code
				});
				if (res) myOpenid = res.openid;
				// #endif
			}
			this.openid = myOpenid
			console.log("myOpenid",myOpenid,this.openid);
		},
		onLoad() {
			this.loadData()
			this.loadHuoban() //加载伙伴信息
			this.loadFensi() //加载粉丝信息
			this.updateUserInfo() //加载可体系金额
		},
		methods: {
			...mapActions(useUserStore, ['updateUserInfo']),
			onClickItem(index) {
				if (this.sindex !== index) {
					this.sindex = index
				}
			},
			tabsClick(e) {
				console.log("e=========>", e);
			},
			async loadHuoban() {
				try{
					let res = await User.getHuoBan({
						level: 1,
						needTotal: true
					})
					console.log("res=========loadHuoban", res)
					// this.items[2] = `${this.items[2]}(${res.total})`
					this.segData[2].value = res.total
					this.huoban = [...res.invitedUser]
				}catch(e){
					console.log("loadHuoban=========loadHuoban", e)
				}
			},
			async loadFensi() { //获取直推粉丝总数，
				let res = await User.getInvitedUser({
					needTotal: true,
					level:1
				})
				console.log("res===========>", res)
				// this.items[3] = `${this.items[3]}(${res.total})`
				this.segData[3].value = res.total
				// this.redList = [...res.invitedUser]
			},
			submit() {
				let price = this.formData.price * 100
				if (price === 0 || price === NaN || (price > this.userInfo.money) || price < 10000) {
					uni.showToast({
						title: '提现金额错误',
						icon: "none"
					})
					return
				}
				if (!this.formData.img.url && this.formData.type===1) {
					uni.showToast({
						title: '请上传提现二维码',
						icon: "none"
					})
					return
				}
				// if(this.formData.type===0 && this.con_price>150000){
				// 	return uni.showToast({
				// 		title: '请填写真实姓名',
				// 		icon: "none"
				// 	})
				// }
				let arr = []
				if(this.formData.type===0 && this.con_price>=40000){//如果是自动提现，并且金额大于400 自动分订单
					let len = parseInt(this.con_price/40000) +1
					let yprice = this.con_price%40000
					console.log("yprice",yprice);
					if(yprice<=30){//剩余金额小0.3元,减少一次循环，将剩余的加到第一次提现订单上
						len = len-1
					}
					for(let i=0;i<len;i++){
						let conprice
						if(i!=len-1){//如果不是最后一次循环
							conprice = 40000
						}else{
							if(yprice<=30){
								conprice = this.con_price-40000*i-yprice
							}else{
								conprice = this.con_price-40000*i
							}
						}
						if(i===0 && yprice <= 30){
							arr.push(this.getOrderList(price,conprice+yprice))
						}else{
							arr.push(this.getOrderList(price,conprice))
						}
					}
				}else{
					arr.push(this.getOrderList(price,this.con_price))
				}
				let money = this.userInfo.money - price
				// return console.log("arr>>>>",arr);
				this.updateUserInfo({
					money
				})
				db.collection('wolf-tixian').add(arr).then(res => {
					uni.showToast({
						title: '已提交',
						icon: "none"
					})
					this.$refs.popup.close()
				})
				console.log("DATA", this.formData)
			},
			getOrderList(price,conprice){
				let now = new Date().getTime() //获取当前时间戳
				let code = '' + (parseInt(Math.random() * 1000000) + 1000000)
				code = code.substring(1, 7)
				let order_no = "TX" + code + now //业务订单号
				let out_batch_no = order_no + 'x1'
				let obj = {
					img: this.formData.img,
					price: price,
					con_price: conprice,
					status: 0,
					uid: this.userInfo._id,
					order_id: order_no,
					create_time: now,
					out_batch_no,
					type: this.formData.type,
					openid:myOpenid,
					name:this.formData.name
				}
				return obj
			},
			/**
			 * 获取code
			 */
			getWeixinCode() {
				return new Promise((resolve, reject) => {
					// #ifdef MP-WEIXIN
					uni.login({
						provider: 'weixin',
						success(res) {
							resolve(res.code)
						},
						fail(err) {
							reject(new Error('获取微信code失败'))
						}
					})
					// #endif
				})
			},
			// 获取code
			async getCode() {
				// #ifdef MP-WEIXIN
				return this.getWeixinCode();
				// #endif
			},
			// 根据code获取openid
			async getOpenid(data = {}) {
				try {
					let res = await uniPayCo.getOpenid(data);
					if (typeof data.success === "function") data.success(res);
					return res;
				} catch (err) {
					if (typeof data.fail === "function") data.fail(err);
				}
			},

			onClick() {
				let week = getWeekDate()
				console.log('w', week)
				// if (week != '周二') {
				// 	uni.showToast({
				// 		title: "请周二再来提现",
				// 		icon: "none"
				// 	})
				// 	return
				// }
				this.$refs.popup.open()
			},
			priceChange() {
				console.log("this.form========>", this.formData.price, this.userInfo.money);
				if (!this.userInfo?.money) {
					this.userInfo.money = 0
				}
				if (this.formData.price * 100 > this.userInfo.money) {
					this.formData.price = this.userInfo.money / 100
				}
			},
			load(data) {
				// console.log(data, this.$refs.udbRef)
			},
			loadData() {
				// db.collection('uni-id-users').where(`isWho == '${this.userInfo._id}' && level>=1`).count().then(res => {
				// 	this.red = res.result.total
				// })
				//查询团队人数
				// db.collection('uni-id-users').where(`inviter_uid == '${this.userInfo._id}'`).count().then(res => {
				// 	// this.items[4] = `${this.items[4]}(${res.result.total})`
				// 	this.segData[4].value = res.result.total
				// })
				User.getInvitedUser({
					needTotal: true,
					level:1
				}).then(res => {
					this.segData[3].value = res.total
				})
				
				db.collection('wolf-profit-order').where(`pid == '${this.userInfo._id}'`).count().then(res => {
					this.orderNum = res.result.total
					this.segData[0].value = res.result.total
				})
				//查询提现订单数量
				db.collection('wolf-tixian').where(this.twhere).count().then(res => {
					this.orderNum = res.result.total
					this.segData[1].value = res.result.total
				})
				//查询可分润幸福值的订单数量
				db.collection('wolf-profit-divvy').where(`pid=="${this.userInfo._id}" && type==1`).count().then(res => {
					this.segData[4].value = res.result.total * 300
				})
			},
			refresh() {
				this.$refs.udbRef.loadData({
					clear: true
				}, () => {
					uni.stopPullDownRefresh()
					console.log('end');
				})
				console.log('refresh');
			},
			loadMore() {
				this.$refs.udbRef.loadMore()
			},
			navigator(id){
				console.log("id===>>>",id);
				if(!id) return
				uni.navigateTo({
					url:`/pages/list/userInfo?id=${id}`
				})
			}
		},
		onPullDownRefresh() {
			this.refresh()
		},
		onReachBottom() {
			this.loadMore()
		}
	}
</script>

<style scoped lang="scss">
	.nav {
		display: flex;
		padding: 10px;
		justify-content: space-around;
	}

	.nav-item {
		width: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		// border: 1px solid #f7f7f7;
		border-radius: 5px;
		padding: 10px 5px;
		height: 60px;
		justify-content: space-around;
	}

	.num {
		color: #fd0d04;
	}

	.box {
		display: flex;
		width: 100%;
	}

	.body {
		flex: 1;
		font-size: 13px;
		padding-left: 10px;
	}

	.price,
	.bottom {
		width: 150rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.price {
		background-color: #f7f0f0;
		border-radius: 5px;
	}

	.pbox {
		min-height: 300px;
		// width: 750rpx;
		padding: 5px 50px;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		background-color: #f7f7f7;
		border-top-left-radius: 10px;
		border-top-right-radius: 10px;
	}

	.header {
		margin-bottom: 20px;
	}

	.yImage {
		width: 50px;
		height: 50px;
		border-radius: 5px;
	}

	.section {
		display: flex;
		flex: 1;
		justify-content: space-between;
		align-items: center;
		font-size: 13px;
	}

	.item {
		display: flex;
		flex-direction: column;
		margin-left: 3px;
	}


	.seg-box {
		display: flex;
		flex-direction: column;
		align-items: center;
		font-size: 12px;
		padding: 5px;
		border-radius: 5px;
	}

	.active {
		background-color: #fd0d04;
		color: #fff;
	}
</style>